#!/usr/bin/python
# -*- coding: utf8 -*-
import sys
import os
import glob

class Plugin(object):
    """
        Tout les plugins doivent hériter de cette classe !
    """
    capabilities = []
    version="0.2"

    def __repr__(self):
        return '<%s %r>' % (
            self.__class__.__name__,
            self.capabilities
        )

def load_plugins(plugins,cfg):
    """
        Charge le plugin, ou les plugin dans le cas ou plugins n'est pas une liste, 
    """
    if (type(plugins) == type([])):
        for plugin in plugins:
            __import__(plugin, None, None, [''])
    else:
        for files in glob.glob(os.path.join(os.path.dirname(__file__),cfg['plugin_path'] + '_*.py')):
            __import__(files.split(os.sep,-1)[len(files.split(os.sep,-1))-1].split(".",-1)[0],None, None, [''])

def init_plugin_system(cfg):
    """
        Ajoute au sys.path le répertoire des plugins si il n'existe pas 
        et charge le script ensuite
        plugin_path doit être relatif au répertoire du loader /!\ A besoin du / final
    """
    path=os.path.join(os.path.dirname(__file__),cfg['plugin_path'])
    if not path in sys.path:
        sys.path.insert(0, path)
    load_plugins(cfg['plugins'],cfg)
    

def find_plugins():
    """
        Cherche toutes les classes qui ont hérités de Plugin
    """
    return Plugin.__subclasses__()

_instances = {}
def get_plugins_by_handlers(handler):
    result = []
    for plugin in Plugin.__subclasses__():
        if handler in plugin.infos['handlers']:
            if not plugin in _instances:
                _instances[plugin] = plugin()
            result.append(_instances[plugin])
    return result
def get_plugins_by_cmd(cmd):
    result=[]
    for plugin in Plugin.__subclasses__():
        if cmd in plugin.infos['cmd']:
            if not plugin in _instances:
                _instances[plugin] = plugin()
            result.append(_instances[plugin])
    return result